<template>
  <div ref="chartRef" style="width: 100%; height: 100%; background: white"></div>
</template>

<script setup>
import { onMounted, ref, watch, onUnmounted } from 'vue';
import * as echarts from 'echarts';

const props = defineProps({
  options: {
    type: Object,
    required: true,
  },
});

const chartRef = ref(null);
let chartInstance = null;

onMounted(() => {
  if (chartRef.value) {
    // eslint-disable-next-line import/namespace
    chartInstance = echarts.init(chartRef.value);
    chartInstance.setOption(props.options);
    chartInstance.resize();
  }
});

watch(
  () => props.options,
  newOptions => {
    if (chartInstance) {
      chartInstance.setOption(newOptions);
    }
  },
  { deep: true },
);

onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose();
    chartInstance = null;
  }
});

defineExpose({
  resize: () => {
    if (chartInstance) {
      chartInstance.resize();
    }
  },
});
</script>
